package net.tngou.jtdb.sql;


import net.tngou.jtdb.netty.TngouClient;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class DBManager {
	static ObjectPool<TngouClient> pool = null;
	private static Log log = LogFactory.getLog(DBManager.class);
	public static TngouClient getConnection() {
		 try {
			 
			 if(pool==null)
			 {
				 _getPool();
			 }
			
			 return pool.borrowObject();
					
			} catch (Exception e) {
				log.error("取得连接失败！");
				e.printStackTrace();
			}
		return null;
	}

	public static void closeConnection(TngouClient tngouClient) {
		
		try {
			
			 if(pool==null)
			 {
				 _getPool();
			 }
			
			pool.returnObject(tngouClient);
			log.info("回收连接！");
		} catch (Exception e) {
			log.error("回收连接失败！");
			e.printStackTrace();
		}
		
	}
	
	public static void close(TngouClient tngouClient) {
		
		try {
			tngouClient.close();
			pool.clear();
			pool.close();
			pool=null;
			log.info("关闭连接！");
		} catch (Exception e) {
			log.error("关闭连接失败！");
			e.printStackTrace();
		}
		
	}


private static  void _getPool() {
	PooledObjectFactory<TngouClient> factory = new DataSourcePoolableObjectFactory();
	GenericObjectPoolConfig config = new GenericObjectPoolConfig() ; 
	config.setLifo(false);
	config.setMaxIdle(5);
	config.setMinIdle(2);
	config.setMaxTotal(10);
	config.setMaxWaitMillis(5 * 1000);
	pool = new GenericObjectPool<TngouClient>(factory, config); 
	log.info("创建连接池！");
	
}
}
